import { ValidationPipe } from '@nestjs/common';
import { ValidationError } from 'class-validator';
import { Class_HttpException_Base } from '../classes/httpException';

/**
 * @description 针对class-validator抛出的错误的message是数组的情况，自定义验证管道类，用于处理验证错误并抛出自定义的 HTTP 异常。
 * @extends {ValidationPipe}
 */
export class Pipe_ValidatorErrorHander_Base extends ValidationPipe {
  constructor() {
    super({
      transform: true,
      whitelist: true,
      exceptionFactory: (errors: ValidationError[]) => {
        const errorArray = [];
        errors.map((err) => {
          for (const item in err.constraints) {
            errorArray.push(err.constraints[item]);
          }
        });
        const errorString = errorArray.join(',');
        return new Class_HttpException_Base(errorString);
      },
    });
  }
}
